/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JanelaPrincipal.java
 *
 * Created on 28/09/2011, 20:32:25
 */
package interfaceplantaserial;

import ch.randelshofer.quaqua.QuaquaLookAndFeel;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jfree.chart.ChartPanel;

/**
 *
 * @author J.Felipe
 */
public class JanelaPrincipal extends javax.swing.JFrame {
    
    /** Atributo para gerenciar a conexão serial. */
    private ConexaoSerial conexaoSerial;
    
    /** Atributo para plotar os gráficos da planta. */
    GraficoSerial graficoPlanta;
    
    /** Creates new form JanelaPrincipal */
    public JanelaPrincipal() {
        try {
            UIManager.setLookAndFeel(new QuaquaLookAndFeel());  
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(JanelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
        
        graficoPlanta = new GraficoSerial();
        panelGrafico.add(new ChartPanel(graficoPlanta.getChart()));
        
        conexaoSerial = new ConexaoSerial(9600, 0);
        
        //Adicionando todas as portas seriais disponíveis no combo de seleção.
        for ( String porta : conexaoSerial.getPortasDisponiveis()) {
            comboPortaSerial.addItem(porta);
        }
        
        loading.setVisible(false);
        sliderPosicao.setEnabled(false);
        
        //Centraliza a janela principal. 
        setLocationRelativeTo(null);
        
        //Seta o ícone da aplicação.
	        URL url = this.getClass().getResource("/img/asterisk_orange.png");  
        Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url);  
        this.setIconImage(imagemTitulo);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        configuracoes = new javax.swing.JFrame();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        parityBox = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        baudRateSpinner = new javax.swing.JSpinner();
        salvarConfigurações = new javax.swing.JButton();
        stopBox = new javax.swing.JComboBox();
        bitsDadosBox = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        painelConexao = new javax.swing.JPanel();
        comboPortaSerial = new javax.swing.JComboBox();
        buttonConectarPorta = new javax.swing.JButton();
        loading = new javax.swing.JLabel();
        painel = new javax.swing.JPanel();
        painelPlantas = new javax.swing.JTabbedPane();
        planta1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        sliderPosicao = new javax.swing.JSlider();
        valorPosicao = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        planta2 = new javax.swing.JPanel();
        planta3 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        toolSair = new javax.swing.JButton();
        jToggleButton1 = new javax.swing.JToggleButton();
        painelConexao1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        kpField = new javax.swing.JTextField();
        kiField = new javax.swing.JTextField();
        kdField = new javax.swing.JTextField();
        panelGrafico = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        buttonConfigurar = new javax.swing.JMenuItem();
        buttonSair = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        configuracoes.setResizable(false);

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 12));
        jLabel4.setText("Baud Rate:");

        jLabel5.setFont(new java.awt.Font("Calibri", 0, 12));
        jLabel5.setText("Bit de Parada:");

        parityBox.setFont(new java.awt.Font("Calibri", 0, 12));
        parityBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nenhum", "Par", "Impar", "Marca", "Espaço" }));

        jLabel6.setFont(new java.awt.Font("Calibri", 0, 12));
        jLabel6.setText("Paridade:");

        baudRateSpinner.setFont(new java.awt.Font("Calibri", 0, 12));

        salvarConfigurações.setFont(new java.awt.Font("Calibri", 0, 12));
        salvarConfigurações.setText("Salvar");
        salvarConfigurações.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarConfiguraçõesActionPerformed(evt);
            }
        });

        stopBox.setFont(new java.awt.Font("Calibri", 0, 12));
        stopBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "1.5", "2" }));

        bitsDadosBox.setFont(new java.awt.Font("Calibri", 0, 12));
        bitsDadosBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5", "6", "7", "8" }));

        jLabel7.setFont(new java.awt.Font("Calibri", 0, 12));
        jLabel7.setText("Bits de Dados:");

        javax.swing.GroupLayout configuracoesLayout = new javax.swing.GroupLayout(configuracoes.getContentPane());
        configuracoes.getContentPane().setLayout(configuracoesLayout);
        configuracoesLayout.setHorizontalGroup(
            configuracoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(configuracoesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addGap(5, 5, 5)
                .addComponent(baudRateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addGap(5, 5, 5)
                .addComponent(parityBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addComponent(jLabel5)
                .addGap(5, 5, 5)
                .addComponent(stopBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bitsDadosBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(salvarConfigurações)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        configuracoesLayout.setVerticalGroup(
            configuracoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(configuracoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(configuracoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(configuracoesLayout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jLabel4))
                    .addGroup(configuracoesLayout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jLabel6))
                    .addGroup(configuracoesLayout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(parityBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(configuracoesLayout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jLabel5))
                    .addGroup(configuracoesLayout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addGroup(configuracoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(stopBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7)
                            .addComponent(bitsDadosBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(salvarConfigurações)))
                    .addGroup(configuracoesLayout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(baudRateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Gerenciador de Plantas");
        setFont(new java.awt.Font("Calibri", 0, 10));
        setIconImages(null);

        painelConexao.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Conexão", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 0, 12))); // NOI18N
        painelConexao.setFont(new java.awt.Font("Calibri", 0, 11));
        painelConexao.setLayout(new javax.swing.BoxLayout(painelConexao, javax.swing.BoxLayout.LINE_AXIS));

        comboPortaSerial.setFont(new java.awt.Font("Calibri", 0, 12));
        comboPortaSerial.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Selecione--" }));
        painelConexao.add(comboPortaSerial);

        buttonConectarPorta.setFont(new java.awt.Font("Calibri", 0, 12));
        buttonConectarPorta.setText("Conectar");
        buttonConectarPorta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonConectarPortaActionPerformed(evt);
            }
        });
        painelConexao.add(buttonConectarPorta);

        loading.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ajax-loader2.gif"))); // NOI18N
        painelConexao.add(loading);

        painel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        painel.setMinimumSize(new java.awt.Dimension(100, 82));

        painelPlantas.setFont(new java.awt.Font("Calibri", 0, 12));

        jLabel2.setFont(new java.awt.Font("Calibri", 1, 12));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Controle de Posição");

        sliderPosicao.setMaximum(179);
        sliderPosicao.setValue(0);
        sliderPosicao.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                sliderPosicaoStateChanged(evt);
            }
        });

        valorPosicao.setFont(new java.awt.Font("Calibri", 0, 12));
        valorPosicao.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        valorPosicao.setText("0");

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 12));
        jLabel3.setText("graus");

        jButton2.setFont(new java.awt.Font("Calibri", 0, 12));
        jButton2.setText("Enviar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout planta1Layout = new javax.swing.GroupLayout(planta1);
        planta1.setLayout(planta1Layout);
        planta1Layout.setHorizontalGroup(
            planta1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(planta1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(planta1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(planta1Layout.createSequentialGroup()
                        .addGroup(planta1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(sliderPosicao, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, planta1Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(valorPosicao, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(10, 10, 10))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, planta1Layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                        .addContainerGap())))
            .addGroup(planta1Layout.createSequentialGroup()
                .addGap(93, 93, 93)
                .addComponent(jButton2)
                .addContainerGap(94, Short.MAX_VALUE))
        );
        planta1Layout.setVerticalGroup(
            planta1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(planta1Layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(planta1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(planta1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sliderPosicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(valorPosicao))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addGap(26, 26, 26))
        );

        painelPlantas.addTab("Planta 1", planta1);

        javax.swing.GroupLayout planta2Layout = new javax.swing.GroupLayout(planta2);
        planta2.setLayout(planta2Layout);
        planta2Layout.setHorizontalGroup(
            planta2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 252, Short.MAX_VALUE)
        );
        planta2Layout.setVerticalGroup(
            planta2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 142, Short.MAX_VALUE)
        );

        painelPlantas.addTab("Planta 2", planta2);

        javax.swing.GroupLayout planta3Layout = new javax.swing.GroupLayout(planta3);
        planta3.setLayout(planta3Layout);
        planta3Layout.setHorizontalGroup(
            planta3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 252, Short.MAX_VALUE)
        );
        planta3Layout.setVerticalGroup(
            planta3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 142, Short.MAX_VALUE)
        );

        painelPlantas.addTab("Planta 3", planta3);

        javax.swing.GroupLayout painelLayout = new javax.swing.GroupLayout(painel);
        painel.setLayout(painelLayout);
        painelLayout.setHorizontalGroup(
            painelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(painelPlantas)
                .addContainerGap())
        );
        painelLayout.setVerticalGroup(
            painelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelLayout.createSequentialGroup()
                .addComponent(painelPlantas, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cog_go.png"))); // NOI18N
        jButton1.setToolTipText("Configurações");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        toolSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/logout-icon.png"))); // NOI18N
        toolSair.setToolTipText("Sair");
        toolSair.setFocusable(false);
        toolSair.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        toolSair.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        toolSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toolSairActionPerformed(evt);
            }
        });
        jToolBar1.add(toolSair);

        jToggleButton1.setText("ON");
        jToggleButton1.setFocusable(false);
        jToggleButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToggleButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jToggleButton1);

        painelConexao1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Variáveis da Planta", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 0, 12))); // NOI18N
        painelConexao1.setFont(new java.awt.Font("Calibri", 0, 11));

        jLabel1.setFont(new java.awt.Font("Calibri", 0, 12));
        jLabel1.setText("Kp:");

        jLabel8.setFont(new java.awt.Font("Calibri", 0, 12));
        jLabel8.setText("Ki:");

        jLabel9.setFont(new java.awt.Font("Calibri", 0, 12));
        jLabel9.setText("Kd:");

        kpField.setText("20");
        kpField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                kpFieldKeyReleased(evt);
            }
        });

        kiField.setText("1");

        kdField.setText("1");

        javax.swing.GroupLayout painelConexao1Layout = new javax.swing.GroupLayout(painelConexao1);
        painelConexao1.setLayout(painelConexao1Layout);
        painelConexao1Layout.setHorizontalGroup(
            painelConexao1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelConexao1Layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(kpField, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(kiField, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(kdField, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(40, Short.MAX_VALUE))
        );
        painelConexao1Layout.setVerticalGroup(
            painelConexao1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelConexao1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(painelConexao1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel8)
                    .addComponent(kiField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(kdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(kpField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        panelGrafico.setBorder(javax.swing.BorderFactory.createTitledBorder("Gráficos"));
        panelGrafico.setLayout(new java.awt.BorderLayout());

        jMenuBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jMenuBar1.setFont(new java.awt.Font("Calibri", 0, 11));

        jMenu1.setText("Arquivo");
        jMenu1.setFont(new java.awt.Font("Calibri", 0, 14));

        buttonConfigurar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cog_go.png"))); // NOI18N
        buttonConfigurar.setText("Configurações");
        buttonConfigurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonConfigurarActionPerformed(evt);
            }
        });
        jMenu1.add(buttonConfigurar);

        buttonSair.setFont(new java.awt.Font("Calibri", 0, 12));
        buttonSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/logout-icon.png"))); // NOI18N
        buttonSair.setText("Sair");
        buttonSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSairActionPerformed(evt);
            }
        });
        jMenu1.add(buttonSair);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ajuda");
        jMenu2.setFont(new java.awt.Font("Calibri", 0, 14));
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 677, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(painelConexao1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(painelConexao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(17, 17, 17)
                .addComponent(panelGrafico, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {painel, painelConexao, painelConexao1});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(painelConexao, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(painelConexao1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(painel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(panelGrafico, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSairActionPerformed

        Object[] opcoes = {"Sim", "Não"};         int resposta = JOptionPane.showOptionDialog(null, "Tem certeza que deseja sair?", "Sair",                 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opcoes, opcoes[1]);         if (resposta == JOptionPane.YES_OPTION) {             dispose();         }     }//GEN-LAST:event_buttonSairActionPerformed

    private void buttonConectarPortaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonConectarPortaActionPerformed
        if (comboPortaSerial.getSelectedIndex() == 0){
            JOptionPane.showMessageDialog(null, "Selecione uma porta para abrir conexão.", "Atenção", 2);
            return;
        }
        if(conexaoSerial.isConexaoAtiva()){
            conexaoSerial.fecharConexao();
            buttonConectarPorta.setText("Conectar");
            comboPortaSerial.setEnabled(true);
            loading.setVisible(false);
            sliderPosicao.setEnabled(false);
        } else {
            try {
                conexaoSerial.abrirConexao(comboPortaSerial.getSelectedItem().toString());
                buttonConectarPorta.setText("Desconectar");
                comboPortaSerial.setEnabled(false);
                loading.setVisible(true);
                sliderPosicao.setEnabled(true); 
            } catch (PortInUseException ex) {
                    JOptionPane.showMessageDialog(null, "A porta selecionada já está em uso.", "Erro", 0);
                return;
            } catch (UnsupportedCommOperationException ex) {
                return;
            }
        }
    }//GEN-LAST:event_buttonConectarPortaActionPerformed

    private void sliderPosicaoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_sliderPosicaoStateChanged
        valorPosicao.setText(String.valueOf(sliderPosicao.getValue()));
    }//GEN-LAST:event_sliderPosicaoStateChanged

    private void buttonConfigurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonConfigurarActionPerformed
        URL url = this.getClass().getResource("/img/cog_go.png");  
        Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url);  
        configuracoes.setIconImage(imagemTitulo);
        configuracoes.setTitle("Configurações");
        configuracoes.setSize(715, 70);
        configuracoes.setLocationRelativeTo(null);
        configuracoes.setVisible(true);
    }//GEN-LAST:event_buttonConfigurarActionPerformed

    private void toolSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toolSairActionPerformed
        buttonSairActionPerformed(evt);
    }//GEN-LAST:event_toolSairActionPerformed
    
    private Integer getIntFromString(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        try {
            return Integer.valueOf(s);
        } catch (NumberFormatException e) {
            return getIntFromString(s.substring(0, s.length() - 1));
        }
    }

    private void salvarConfiguraçõesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarConfiguraçõesActionPerformed
                int baudRate = (Integer) baudRateSpinner.getValue();
                conexaoSerial.setBaudRate(baudRate);
                int paridade = parityBox.getSelectedIndex();
                switch (paridade) {
                    case 0:
                        conexaoSerial.setParidade(conexaoSerial.getPortaAtiva().PARITY_NONE);
                        break;
                    case 1:
                        conexaoSerial.setParidade(conexaoSerial.getPortaAtiva().PARITY_EVEN);
                        break;
                    case 2:
                        conexaoSerial.setParidade(conexaoSerial.getPortaAtiva().PARITY_ODD);
                        break;
                    case 3:
                        conexaoSerial.setParidade(conexaoSerial.getPortaAtiva().PARITY_MARK);
                        break;
                    case 4:
                        conexaoSerial.setParidade(conexaoSerial.getPortaAtiva().PARITY_SPACE);
                        break;
                }
                
                int bitParada = stopBox.getSelectedIndex();
                switch (bitParada) {
                    case 0:
                        conexaoSerial.setStopBit(conexaoSerial.getPortaAtiva().STOPBITS_1);
                        break;
                    case 1:
                        conexaoSerial.setStopBit(conexaoSerial.getPortaAtiva().STOPBITS_1_5);
                        break;
                    case 2:
                        conexaoSerial.setStopBit(conexaoSerial.getPortaAtiva().STOPBITS_2);
                        break;
                }
                
                int bitDados = bitsDadosBox.getSelectedIndex();
                switch (bitDados) {
                    case 0:
                        conexaoSerial.setDataBits(conexaoSerial.getPortaAtiva().DATABITS_5);
                        break;
                    case 1:
                        conexaoSerial.setDataBits(conexaoSerial.getPortaAtiva().DATABITS_6);
                        break;
                    case 2:
                        conexaoSerial.setDataBits(conexaoSerial.getPortaAtiva().DATABITS_7);
                        break;
                    case 3:
                        conexaoSerial.setDataBits(conexaoSerial.getPortaAtiva().DATABITS_8);
                        break;
                }
                configuracoes.setVisible(false);
               
             }//GEN-LAST:event_salvarConfiguraçõesActionPerformed

    private void kpFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_kpFieldKeyReleased
        kpField.setText(getIntFromString(kpField.getText()).toString());
    }//GEN-LAST:event_kpFieldKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        buttonConfigurarActionPerformed(evt);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int escrita = sliderPosicao.getValue();
        try {
            conexaoSerial.escreverPorta((byte) 0, escrita);
//            conexaoSerial.lerPorta();
//            graficoPlanta.setRecebido(Integer.parseInt(conexaoSerial.getMensagem()));
//            graficoPlanta.plotar();

        } catch (IOException ex) {
            Logger.getLogger(JanelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(JanelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed

    }//GEN-LAST:event_jToggleButton1ActionPerformed
private boolean flag = false;
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JanelaPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSpinner baudRateSpinner;
    private javax.swing.JComboBox bitsDadosBox;
    private javax.swing.JButton buttonConectarPorta;
    private javax.swing.JMenuItem buttonConfigurar;
    private javax.swing.JMenuItem buttonSair;
    private javax.swing.JComboBox comboPortaSerial;
    private javax.swing.JFrame configuracoes;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField kdField;
    private javax.swing.JTextField kiField;
    private javax.swing.JTextField kpField;
    private javax.swing.JLabel loading;
    private javax.swing.JPanel painel;
    private javax.swing.JPanel painelConexao;
    private javax.swing.JPanel painelConexao1;
    private javax.swing.JTabbedPane painelPlantas;
    private javax.swing.JPanel panelGrafico;
    private javax.swing.JComboBox parityBox;
    private javax.swing.JPanel planta1;
    private javax.swing.JPanel planta2;
    private javax.swing.JPanel planta3;
    private javax.swing.JButton salvarConfigurações;
    private javax.swing.JSlider sliderPosicao;
    private javax.swing.JComboBox stopBox;
    private javax.swing.JButton toolSair;
    private javax.swing.JLabel valorPosicao;
    // End of variables declaration//GEN-END:variables

    }

